package com.bbva.kyfb.kyfbs.utils;

import java.io.InputStream;

import org.apache.commons.io.IOUtils;
import org.springframework.core.io.Resource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import com.bbva.jee.arq.spring.core.log.I18nLog;
import com.bbva.jee.arq.spring.core.log.I18nLogFactory;


/**
 * The Class KyfbUtils.
 */
@Component
public class KyfbUtils {

	/** LOGGER. */
	private static final I18nLog LOG = I18nLogFactory.getLogI18n(KyfbUtils.class);

	/**
	 * Run sql from script resource.
	 *
	 * @param resource the resource
	 * @param jdbcTemplate the jdbc template
	 */
	@Transactional(rollbackFor = Exception.class, isolation = Isolation.READ_UNCOMMITTED)
	public static void runSqlFromScriptResource(final Resource resource, final JdbcTemplate jdbcTemplate) {
		try {
			final InputStream ipStr = resource.getInputStream();
			final String[] sql = IOUtils.toString(ipStr).split(";");

			for (final String element : sql) {
				try {
					jdbcTemplate.update(element);
				} catch(final Exception e){
					LOG.info(e,"runSqlFromScriptResource",resource,jdbcTemplate);
				}
			}

		} catch (final Exception e) {
			throw new RuntimeException("Unable to run sql script against " + resource.getFilename(), e);
		}
	}



}
